package org.runtimedao.utils;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;


import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.runtimedao.exception.CompilerException;

public class CompilerUtils {

	private static final String BAD_SYNTAX = "Bad syntax";
	private static Logger LOG = Logger.getLogger(CompilerUtils.class);

	public static URI createURI(String str) {
		try {
			LOG.debug("Creating URI from " + str);
			URI uri = new URI(str);
			LOG.debug("URI: " + uri);
			return uri;
		} catch (URISyntaxException e) {
			LOG.error(BAD_SYNTAX, e);
			throw new CompilerException(BAD_SYNTAX, e);
		}
	}

	public static void printClasspath() {
		ClassLoader classLoader = ClassLoader.getSystemClassLoader();

		// Get the URLs
		URL[] urls = ((URLClassLoader) classLoader).getURLs();
		StringBuilder sb = new StringBuilder();
		sb.append("CLASSPATH:\n");
		for (int i = 0; i < urls.length; i++) {
			sb.append(urls[i].getFile()).append("\n");
		}

		LOG.info(sb);
	}

	public static String getQualifiedClassName(String packageName,
			String className) {
		if (StringUtils.isBlank(packageName)) {
			return className;
		}

		return packageName + ConstantsUtils.DOT + className;
	}

	public static String getClassNameWithExtension(String className) {
		return className + Kind.SOURCE.extension;
	}

	public static String getCompilationError(
			DiagnosticCollector<JavaFileObject> collector) {
		StringBuilder sb = new StringBuilder();
		for (Diagnostic<? extends JavaFileObject> diagnostic : collector
				.getDiagnostics()) {
			sb.append(diagnostic.getMessage(null));
			sb.append(ConstantsUtils.SEMI_COLON_SPACE);
		}
		return sb.toString();
	}

}
